const redisClient = require('../utils/redisClient');

/**
 * 自增计数器
 * @param username
 * @param {string} fieldName - 字段名称，默认为 "ai_all_num"
 * @param {number} increment - 自增值，默认为 1
 * @returns {Promise<number>} - 返回自增后的值
 * @throws {RuntimeError} - 如果操作失败，抛出错误
 */
async function setIncrementCounter( username , fieldName = "01", increment = 1) {
    try {
        const hashName = username + "_Increment";
        return await redisClient.hIncrBy(hashName, fieldName, increment);
    } catch (error) {
        throw new Error(`计数失败: ${error.message}`);
    }
}



/**
 * 读取计数业务
 * @returns {Promise<{success: boolean, count?: string, message?: string}>} - 返回计数结果
 * @param username
 */
async function getIncrementCounter(username) {
    try {
        const name = username + "_Increment";
        const count_1 = await redisClient.hGet(name, "01") || "0";
        const count_2 = await redisClient.hGet(name, "02") || "0";
        const count_3 = await redisClient.hGet(name, "03") || "0";

        // 返回所有字段的值，或者根据需求返回特定的字段
        return {
            success: true,
            counts: {
                count_1,
                count_2,
                count_3
            }
        };
    } catch (error) {
        return { success: false, message: `读取计数失败: ${error.message}` };
    }
}



/**
 * 存储用户 Token
 * @param {string} token - 用户 Token
 * @param {string} username - 用户名
 * @returns {Promise<{success: boolean, message: string, count?: number}>} - 返回操作结果
 */
async function storeUserToken( token, username) {
    try {
        const count = await redisClient.hSet('user_tokens', token, username);
        return { success: true, message: `存储成功`, count };
    } catch (error) {
        return { success: false, message: `Failed to store token: ${error.message}` };
    }
}

/**
 * 读取用户 Token
 * @returns {Promise<string>} - 返回操作结果
 */
async function readUserToken(token) {
    try {
        return  await redisClient.hGet('user_tokens', token) ;
    } catch (error) {
        return { success: false, message: `Failed to store token: ${error.message}` };
    }
}


/**
 * 关联设备与 username
 * @returns {Promise<{success: boolean, message: string, count?: number}>} - 返回操作结果
 */
async function associateDeviceWithUser(monitor_id, username) {
    try {
        const count = await redisClient.hSet('monitor_user', monitor_id,  username);
        return { success: true, message: `存储成功`, count };
    } catch (error) {
        return { success: false, message: `Failed to associate device with token: ${error.message}` };
    }
}



module.exports = {
    setIncrementCounter,
    getIncrementCounter,
    readUserToken,
    storeUserToken,
    associateDeviceWithUser,
};